package com.zhuhjay.boot.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zhuhjay.constant.MessageConstant;
import com.zhuhjay.constant.RedisMessageConstant;
import com.zhuhjay.domain.http.Result;
import com.zhuhjay.service.MemberService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhuhjay
 * @since 2022-04-02
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    private final StringRedisTemplate redisTemplate;
    public MemberController(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Reference
    private MemberService memberService;

    @PostMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map<String, Object> map){
        try{
            // 验证码校验
            String code = redisTemplate.opsForValue()
                    .get(RedisMessageConstant.SENDTYPE_LOGIN + ":" + map.get("telephone"));
            String validateCode = (String) map.get("validateCode");
            if( code != null && code.equals(validateCode) ){
                memberService.login(map);
                // 向客户端写出Cookie, 内容为手机号
                Cookie cookie = new Cookie("LOGIN_MEMBER_TELEPHONE", (String) map.get("telephone"));
                cookie.setPath("/");
                cookie.setMaxAge(60 * 60 * 24 * 30);
                response.addCookie(cookie);
            }else{
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
    }

}
